package com.woniuxy.orderservice.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.core.exception.WoniuxyException;
import com.woniuxy.core.model.Result;
import com.woniuxy.core.status.*;
import com.woniuxy.core.util.DateUtil;
import com.woniuxy.core.util.MyJwtUtil;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.orderclient.client.*;
import com.woniuxy.orderclient.client.dto.*;
import com.woniuxy.orderdao.mapper.OrderMapper;
import com.woniuxy.orderdao.model.Order;
import com.woniuxy.orderdao.model.OrderLog;
import com.woniuxy.ordermodel.dto.*;
import com.woniuxy.ordermodel.form.CoachListOrderForm;
import com.woniuxy.ordermodel.form.UserListOrderForm;
import com.woniuxy.ordermodel.form.VenueListOrderForm;
import com.woniuxy.orderservice.exception.OrderException;
import com.woniuxy.orderservice.service.OrderService;
import com.woniuxy.util.MyAlipayUtil;
import com.woniuxy.util.PagePayParam;
import com.woniuxy.util.config.AlipayConfiguration;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 冉杰
 * @since 2024-01-15
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ProductFeignClient pfc;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MyAlipayUtil myAlipayUtil;
    @Autowired
    private AlipayConfiguration alipayConfiguration;
    @Autowired
    private VenueFeignClient vfc;
    @Autowired
    private CardFeignClient cfc;
    @Autowired
    private UserFeignClient ufc;
    @Resource
    private CoachFeignClient coachFeignClient;
    /**
     * 根据教练id查询订单成功
     * @param coachId 教练id
     * @return
     */
    @Override
    public List<CoachListOrderDto> findByCoachId(Integer coachId) {


        List<Order> list = list(new QueryWrapper<Order>().eq("coach_id", coachId));
        List<CoachListOrderDto> dtos = new ArrayList<>();
        if (ObjectUtils.isEmpty(list)) return dtos;
        for (Order order : list) {
            CoachListOrderDto dto = BeanUtil.toBean(order, CoachListOrderDto.class);
            dto.setTypeName(OrderState.searchTypeName(dto.getOrderType()));
            dtos.add(dto);
        }
        return dtos;
    }

    /**
     * 商家端根据商家Id查看订单
     * @param venueId
     * @return
     */
    @Override
    public List<VenueListOrderDto> findByVenueId(Integer venueId) {

        List<Order> list = list(new QueryWrapper<Order>().eq("venue_id", venueId));
        List<VenueListOrderDto> dtos = new ArrayList<>();
        if (ObjectUtils.isEmpty(list)) return dtos;
        for (Order order : list) {
            VenueListOrderDto dto = BeanUtil.toBean(order, VenueListOrderDto.class);
            dto.setTypeName(OrderState.searchTypeName(dto.getOrderType()));
            dtos.add(dto);
        }
        return dtos;
    }

    /**
     * 教练端私教订单下单
     * @param coachReservId
     * @param coachId
     * @return
     */
    @GlobalTransactional(rollbackFor = {Exception.class})
    @Override
    public AloneCourseOrderDto addAloneCourseOrder(Integer coachReservId, Integer coachId) {
        boolean flag = new LambdaQueryChainWrapper<Order>(getBaseMapper())
                .eq(Order::getCoachReservId, coachReservId)
                .ne(Order::getOrderState, OrderState.CANCELED.getState()).exists();
        if (flag) throw new OrderException(40004,"该预约已下订单");
        Result<CoachReservInfoDto> res1 = pfc.findCoachReservById(coachReservId);
        if (!res1.getFlag()) throw new OrderException(res1.getCode(),res1.getMsg());
        CoachReservInfoDto coachReserv = res1.getData();
        if (ObjectUtils.isEmpty(coachReserv)) throw new OrderException(40001,"预约不存在");
        if (coachReserv.getCoachId()!=coachId) throw new OrderException(40002,"不是该教练的预约，下单失败");
        if (!coachReserv.getReservState().equals(CoachReservState.AGREE.getName()))
            throw new OrderException(40003,"教练未同意该预约");
        Result<CoachLoginDto> result = coachFeignClient.searchCoachByCoachId(coachId);
        if (!result.getFlag()) throw new OrderException(result.getCode(),result.getMsg());
        CoachLoginDto coachLoginDto = result.getData();
        Result<VenueLoginDto> venueLoginDtoResult = vfc.byId(coachLoginDto.getVenueId());
        if (!venueLoginDtoResult.getFlag())
            throw new OrderException(venueLoginDtoResult.getCode(),venueLoginDtoResult.getMsg());
        VenueLoginDto venueLoginDto = venueLoginDtoResult.getData();
        //执行下单操作
        Order order = new Order();
        String orderNum = new Snowflake(1, 1).nextIdStr();
        order.setOrderNum(orderNum);
        order.setOrderState(OrderState.NOT_PAY.getState());
        order.setOrderType(OrderState.PERSONAL_COACH_TYPE.getState());
        order.setOrderCreateTime(DateUtil.dateTimeToString(new Date()));
        order.setCoachId(coachId);
        order.setVenueId(coachLoginDto.getVenueId());
        order.setVenuePhone(venueLoginDto.getVenuePhone());
        order.setCoachReservId(coachReservId);
        order.setOrderEvaluationState(OrderState.NOT_EVALUATION.getState());
        order.setProductId(coachReserv.getCoachProductId());
        order.setProductName(coachReserv.getCoachRemark());
        order.setUserName(coachReserv.getUserName());
        order.setUserId(coachReserv.getUserId());
        order.setUserPhone(coachReserv.getUserPhone());
        order.setOrderMoney(coachReserv.getCoachProductPrice());
        save(order);
        AloneCourseOrderDto dto = BeanUtil.toBean(order, AloneCourseOrderDto.class);
        dto.setTypeName(OrderState.searchTypeName(dto.getOrderType()));
        //将订单加入消息队列判断是否支付状态，未支付，自动取消订单
        rabbitTemplate.convertAndSend("coach-order-dead-queue",orderNum);
        rabbitTemplate.convertAndSend("coach-long-order-dead-queue",orderNum);
        OrderLog log = new OrderLog();
        log.setLogUser("教练Id:"+coachId);
        log.setLogDesc("教练下单私教课程");
        log.setLogTime(DateUtil.dateTimeToString(new Date()));
        log.setOrderNum(orderNum);
        rabbitTemplate.convertAndSend("order-log-queue",log);
        return dto;
    }

    /**
     * 根据订单号查找订单详情
     * @param orderNum
     * @return
     */
    @Override
    public OrderDto findByOrderNum(String orderNum) {
        Order order = getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNum, orderNum));
        return BeanUtil.toBean(order, OrderDto.class);
    }

    /**
     * 用户端取消私教课订单
     * @param orderNum
     * @param token
     */
    @Override
    public void cancelAloneCourse(String orderNum, String token) {
        Integer userId = MyJwtUtil.getUserIdByKey(token, "userId");
        Order orderInfo = getById(orderNum);
        if (ObjectUtils.isEmpty(orderInfo)) throw new OrderException(40001,"订单不存在");
        if (orderInfo.getUserId()!=userId) throw new OrderException(40002,"不是自己的订单");
        if(orderInfo.getOrderType()!=OrderState.PERSONAL_COACH_TYPE.getState()) throw new OrderException(40003,"不是私教订单");
        if (orderInfo.getOrderState()!=OrderState.NOT_PAY.getState()) throw new OrderException(40004,"只能取消待支付状态的订单");
        orderInfo.setOrderState(OrderState.CANCELED.getState());
        updateById(orderInfo);
        OrderLog log = new OrderLog();
        log.setLogUser(orderInfo.getUserName()+":"+orderInfo.getUserPhone());
        log.setLogDesc("用户取消了私教订单");
        log.setLogTime(DateUtil.dateTimeToString(new Date()));
        log.setOrderNum(orderNum);
        rabbitTemplate.convertAndSend("order-log-queue",log);
    }

    /**
     * 用户端查看自己订单
     * @param form
     * @param userId
     * @return
     */
    @Override
    public PageInfo<UserCourseOrderDto> userListOrder(UserListOrderForm form, Integer userId) {
        Long current = form.getCurrent();
        Long size = form.getSize();
        Page<Order> page = new Page<>(current==null?1l:current, size==null?6l:size);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .eq(!ObjectUtils.isEmpty(form.getOrderType()), Order::getOrderType, form.getOrderType())
                .eq(!ObjectUtils.isEmpty(form.getOrderNum()), Order::getOrderNum, form.getOrderNum())
                .eq(!ObjectUtils.isEmpty(form.getVenuePhone()), Order::getVenuePhone, form.getVenuePhone())
                .like(!ObjectUtils.isEmpty(form.getProductName()), Order::getProductName, form.getProductName())
                .orderByDesc(Order::getOrderCreateTime);
        getBaseMapper().selectPage(page,wrapper);
        List<Order> orders = page.getRecords();
        List<UserCourseOrderDto> dtos = BeanUtil.copyToList(orders, UserCourseOrderDto.class);
        for (UserCourseOrderDto dto : dtos) {
            dto.setTypeName(OrderState.searchTypeName(dto.getOrderType()));
        }
        PageInfo<UserCourseOrderDto> pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(dtos);
        return pageInfo;
    }

    /**
     * 教练端查看订单详情
     * @param form
     * @param coachId
     * @return
     */
    @Override
    public PageInfo<CoachListOrderDto> coachListOrder(CoachListOrderForm form, Integer coachId) {
        Long current = form.getCurrent();
        Long size = form.getSize();
        Page<Order> page = new Page<>(current==null?1l:current, size==null?6l:size);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>()
                .eq(Order::getCoachId, coachId)
                .eq(!ObjectUtils.isEmpty(form.getOrderType()), Order::getOrderType, form.getOrderType())
                .eq(!ObjectUtils.isEmpty(form.getOrderNum()), Order::getOrderNum, form.getOrderNum())
                .eq(!ObjectUtils.isEmpty(form.getUserPhone()), Order::getVenuePhone, form.getUserPhone())
                .like(!ObjectUtils.isEmpty(form.getProductName()), Order::getProductName, form.getProductName())
                .orderByDesc(Order::getOrderCreateTime);
        getBaseMapper().selectPage(page,wrapper);
        List<Order> orders = page.getRecords();
        List<CoachListOrderDto> dtos = BeanUtil.copyToList(orders, CoachListOrderDto.class);
        for (CoachListOrderDto dto : dtos) {
            dto.setTypeName(OrderState.searchTypeName(dto.getOrderType()));
        }
        PageInfo<CoachListOrderDto> pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(dtos);
        return pageInfo;
    }

    /**
     * 商家端查看自己订单详情
     * @param form
     * @param venueId
     * @return
     */
    @Override
    public PageInfo<VenueListOrderDto> venueListOrder(VenueListOrderForm form, Integer venueId) {
        Long current = form.getCurrent();
        Long size = form.getSize();
        Page<Order> page = new Page<>(current==null?1l:current, size==null?6l:size);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>()
                .eq(Order::getVenueId, venueId)
                .eq(!ObjectUtils.isEmpty(form.getOrderType()), Order::getOrderType, form.getOrderType())
                .eq(!ObjectUtils.isEmpty(form.getOrderNum()), Order::getOrderNum, form.getOrderNum())
                .eq(!ObjectUtils.isEmpty(form.getUserPhone()), Order::getVenuePhone, form.getUserPhone())
                .like(!ObjectUtils.isEmpty(form.getProductName()), Order::getProductName, form.getProductName())
                .orderByDesc(Order::getOrderCreateTime);
        getBaseMapper().selectPage(page,wrapper);
        List<Order> orders = page.getRecords();
        List<VenueListOrderDto> dtos = BeanUtil.copyToList(orders, VenueListOrderDto.class);
        for (VenueListOrderDto dto : dtos) {
            dto.setTypeName(OrderState.searchTypeName(dto.getOrderType()));
        }
        PageInfo<VenueListOrderDto> pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(dtos);
        return pageInfo;
    }

    /**
     * 用户发起支付
     * @param orderNum 订单号
     * @return
     */
    @Override
    public String pagePay(String orderNum) throws Exception {
        Order order = getById(orderNum);
        if (ObjectUtils.isEmpty(order)) throw new OrderException(50001,"订单不存在");
        if (order.getOrderState()!=OrderState.NOT_PAY.getState()) throw new OrderException(50002,"订单不是待支付状态");
        PagePayParam param = new PagePayParam();
        param.setOrderId(orderNum);
        param.setMoney(order.getOrderMoney().doubleValue());
        param.setSubject("瑜伽馆项目支付服务");
        param.setBody("购买课程支付");
        param.setReturnUrl("http://192.168.20.111:9001/swagger-ui.html/");
        //回调接口根据不同类型的订单跳转访问不同的回调接口
        if (order.getOrderType()==OrderState.PERSONAL_COACH_TYPE.getState()){
            //私教订单
            param.setNotifyUrl("http://pc238m.natappfree.cc/order/orderInfo/notifyCoach");
        } else if (order.getOrderType()==OrderState.GROUP_TYPE.getState()) {
            //团教订单
            param.setNotifyUrl("http://pc238m.natappfree.cc/order/orderInfo/notifyTeam");
        } else if (order.getOrderType()==OrderState.COUNT_CARD_TYPE.getState()) {
            //次卡订单
            param.setNotifyUrl("http://pc238m.natappfree.cc/order/orderInfo/notifyCountCard");
        } else if (order.getOrderType()==OrderState.VALID_CARD_TYPE.getState()) {
            //有效期卡订单
            param.setNotifyUrl("http://pc238m.natappfree.cc/order/orderInfo/notifyValidCard");
        }
        String html = myAlipayUtil.pagePay(param);
        return html;
    }

    /**
     * 私教订单回调
     * @param params
     */
    @Override
    public void notifyCoachHandler(Map<String, String> params) throws AlipayApiException {
        //验签，校验支付宝方的请求是不是伪造的
        boolean rsa2 = AlipaySignature.rsaCheckV1(params, alipayConfiguration.getAlipayPublicKey(), "utf-8", "RSA2");
        if (!rsa2) throw new WoniuxyException(500, "伪造非法请求，执行失败");
        String orderNum = params.get("out_trade_no");
        Order orderInfo = getById(orderNum);
        //改订单状态
        orderInfo.setOrderState(OrderState.IS_PAID.getState());//已购买
        orderInfo.setOrderPayTime(DateUtil.dateTimeToString(new Date()));
        updateById(orderInfo);
        //记录日志
        OrderLog log = new OrderLog();
        log.setLogUser("支付宝异步回调私教订单操作");
        log.setLogDesc("订单已支付");
        log.setLogTime(DateUtil.dateTimeToString(new Date()));
        log.setOrderNum(orderNum);
        rabbitTemplate.convertAndSend("order-log-queue",log);
        rabbitTemplate.convertAndSend("coach-order-process-queue",orderNum);//生成私教订单进度
    }

    /**
     * 用户团课下单
     * @param teamReservId 团课预约id
     * @param userId
     * @return
     */
    @GlobalTransactional(rollbackFor = {Exception.class})
    @Override
    public TeamCourseOrderDto addTeamCourseOrder(Integer teamReservId, Integer userId) {
        Result<TeamReservDto> res1 = pfc.findTeamReservationById(teamReservId);
        if (!res1.getFlag()) throw new OrderException(res1.getCode(),res1.getMsg());
        TeamReservDto teamReserv = res1.getData();
        if (ObjectUtils.isEmpty(teamReserv)) throw new OrderException(50002,"预约不存在");
        if (teamReserv.getUserId()!=userId) throw new OrderException(50003,"不是该用户的预约");
        if (teamReserv.getReservationState()!= TeamResevState.OPEN_CLASS.getState()) throw new OrderException(50004,"该预约还没开课不能下单");
        Order OrderInfo = getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .eq(Order::getTeamReservId, teamReservId));
        if (!ObjectUtils.isEmpty(OrderInfo)) throw new OrderException(50005,"该预约已经下过单了");
        //拼装订单对象
        Result<TeamProductDto> res2 = pfc.findTeamProductById(teamReserv.getTeamProductId());
        if (!res2.getFlag()) throw new OrderException(res2.getCode(),res2.getMsg());
        TeamProductDto teamProduct = res2.getData();
        if (ObjectUtils.isEmpty(teamProduct)) throw new OrderException(50006,"产品不存在");
        Result<VenueLoginDto> res3 = vfc.byId(teamReserv.getVenueId());
        if (!res3.getFlag()) throw new OrderException(res3.getCode(),res3.getMsg());
        VenueLoginDto venue = res3.getData();
        if (ObjectUtils.isEmpty(venue)) throw new OrderException(50007,"场馆不存在");
        Order order = new Order();
        String orderNum = new Snowflake(1, 1).nextIdStr();
        order.setOrderNum(orderNum);
        order.setOrderState(OrderState.NOT_PAY.getState());
        order.setOrderType(OrderState.GROUP_TYPE.getState());
        order.setOrderCreateTime(DateUtil.dateTimeToString(new Date()));
        order.setCoachId(teamProduct.getCoachId());
        order.setTeamReservId(teamReservId);
        order.setOrderEvaluationState(OrderState.NOT_EVALUATION.getState());
        order.setProductId(teamProduct.getTeamProductId());
        order.setProductName(teamProduct.getTeamProductName());
        order.setUserName(teamReserv.getUserName());
        order.setUserId(teamReserv.getUserId());
        order.setUserPhone(teamReserv.getUserPhone());
        order.setOrderMoney(teamProduct.getTeamProductPrice());
        order.setVenueId(venue.getVenueId());
        order.setVenuePhone(venue.getVenuePhone());
        save(order);
        //将订单加入消息队列判断是否支付状态，未支付，自动取消订单
        rabbitTemplate.convertAndSend("team-order-dead-queue",orderNum);
        OrderLog log = new OrderLog();
        log.setLogUser(teamReserv.getUserName()+":"+teamReserv.getUserPhone());
        log.setLogDesc("用户团课下单");
        log.setLogTime(DateUtil.dateTimeToString(new Date()));
        log.setOrderNum(orderNum);
        rabbitTemplate.convertAndSend("order-log-queue",log);
        TeamCourseOrderDto dto = BeanUtil.toBean(order, TeamCourseOrderDto.class);
        dto.setTypeName(OrderState.searchTypeName(dto.getOrderType()));
        return dto;
    }

    /**
     * 团课异步回调接口
     * @param params
     * @throws AlipayApiException
     */
    @Override
    public void notifyTeamHandler(Map<String, String> params) throws AlipayApiException {
        //验签，校验支付宝方的请求是不是伪造的
        boolean rsa2 = AlipaySignature.rsaCheckV1(params, alipayConfiguration.getAlipayPublicKey(), "utf-8", "RSA2");
        if (!rsa2) throw new WoniuxyException(500, "伪造非法请求，执行失败");
        String orderNum = params.get("out_trade_no");
        Order orderInfo = getById(orderNum);
        //改订单状态
        orderInfo.setOrderState(OrderState.IS_PAID.getState());//已购买
        orderInfo.setOrderPayTime(DateUtil.dateTimeToString(new Date()));
        updateById(orderInfo);
        //记录日志
        OrderLog log = new OrderLog();
        log.setLogUser("支付宝异步回调团课订单操作");
        log.setLogDesc("订单已支付");
        log.setLogTime(DateUtil.dateTimeToString(new Date()));
        log.setOrderNum(orderNum);
        rabbitTemplate.convertAndSend("order-log-queue",log);
        rabbitTemplate.convertAndSend("team-order-process-queue",orderNum);//生成私教订单进度
    }

    /**
     * 用户次卡下单
     * @param cardId
     * @param userId
     * @return
     */
    @GlobalTransactional(rollbackFor = {Exception.class})
    @Override
    public CountCardOrderDto addCountCardOrder(Integer cardId, Integer userId) {
        Result<CountCardDto> res1 = cfc.findCountCardById(cardId);
        if (!res1.getFlag()) throw new OrderException(res1.getCode(),res1.getMsg());
        CountCardDto countCard = res1.getData();
        if (ObjectUtils.isEmpty(countCard)) throw new OrderException(50002,"次卡不存在");
        if (countCard.getCardState()!= CardState.IS_ENABLE.getState()) throw new OrderException(50003,"次卡未启用");
        Result<UserInfoDto> res2 = ufc.findUserById(userId);
        if (!res2.getFlag()) throw new OrderException(res2.getCode(),res2.getMsg());
        UserInfoDto userInfo = res2.getData();
        if (ObjectUtils.isEmpty(userInfo)) throw new OrderException(50004,"用户不存在");
        if (userInfo.getUserState()!= UserState.IS_ENABLE.getState()) throw new OrderException(50005,"用户未启用");
        if (userInfo.getAuthState()!=UserState.IS_AUTH.getState()) throw new OrderException(50006,"用户未实名认证");
        Result<VenueLoginDto> res3 = vfc.byId(countCard.getVenueId());
        if (!res3.getFlag()) throw new OrderException(res3.getCode(),res3.getMsg());
        VenueLoginDto venue = res3.getData();
        if (ObjectUtils.isEmpty(venue)) throw new OrderException(50007,"场馆不存在");
        Order order = new Order();
        String orderNum = new Snowflake(1, 1).nextIdStr();
        order.setOrderState(OrderState.NOT_PAY.getState());
        order.setOrderEvaluationState(OrderState.NOT_EVALUATION.getState());
        order.setOrderNum(orderNum);
        order.setOrderCreateTime(DateUtil.dateTimeToString(new Date()));
        order.setUserId(userId);
        order.setUserName(userInfo.getUserName());
        order.setUserPhone(userInfo.getUserPhone());
        order.setVenueId(countCard.getVenueId());
        order.setVenuePhone(venue.getVenuePhone());
        order.setProductId(countCard.getCardId());
        order.setProductName(countCard.getCardName());
        order.setOrderMoney(countCard.getCardPrice());
        order.setOrderType(OrderState.COUNT_CARD_TYPE.getState());//次卡类型
        save(order);
        rabbitTemplate.convertAndSend("card-order-dead-queue",orderNum);
        //记录日志
        OrderLog log = new OrderLog();
        log.setLogUser(userInfo.getUserName()+":"+userInfo.getUserPhone());
        log.setLogDesc("用户次卡下订单");
        log.setLogTime(DateUtil.dateTimeToString(new Date()));
        log.setOrderNum(orderNum);
        rabbitTemplate.convertAndSend("order-log-queue",log);
        CountCardOrderDto dto = BeanUtil.toBean(order, CountCardOrderDto.class);
        return dto;
    }

    @Override
    public ValidCardOrderDto addValidCardOrder(Integer cardId, Integer userId) {
        Result<ValidCardDto> res1 = cfc.findValidCardById(cardId);
        if (!res1.getFlag()) throw new OrderException(res1.getCode(),res1.getMsg());
        ValidCardDto validCard = res1.getData();
        if (ObjectUtils.isEmpty(validCard)) throw new OrderException(50002,"有效期卡不存在");
        if (validCard.getCardState()!= CardState.IS_ENABLE.getState()) throw new OrderException(50003,"有效期卡未启用");
        Result<UserInfoDto> res2 = ufc.findUserById(userId);
        if (!res2.getFlag()) throw new OrderException(res2.getCode(),res2.getMsg());
        UserInfoDto userInfo = res2.getData();
        if (ObjectUtils.isEmpty(userInfo)) throw new OrderException(50004,"用户不存在");
        if (userInfo.getUserState()!= UserState.IS_ENABLE.getState()) throw new OrderException(50005,"用户未启用");
        if (userInfo.getAuthState()!=UserState.IS_AUTH.getState()) throw new OrderException(50006,"用户未实名认证");
        Result<VenueLoginDto> res3 = vfc.byId(validCard.getVenueId());
        if (!res3.getFlag()) throw new OrderException(res3.getCode(),res3.getMsg());
        VenueLoginDto venue = res3.getData();
        if (ObjectUtils.isEmpty(venue)) throw new OrderException(50007,"场馆不存在");
        Order order = new Order();
        String orderNum = new Snowflake(1, 1).nextIdStr();
        order.setOrderState(OrderState.NOT_PAY.getState());
        order.setOrderEvaluationState(OrderState.NOT_EVALUATION.getState());
        order.setOrderNum(orderNum);
        order.setOrderCreateTime(DateUtil.dateTimeToString(new Date()));
        order.setUserId(userId);
        order.setUserName(userInfo.getUserName());
        order.setUserPhone(userInfo.getUserPhone());
        order.setVenueId(validCard.getVenueId());
        order.setVenuePhone(venue.getVenuePhone());
        order.setProductId(validCard.getCardId());
        order.setProductName(validCard.getCardName());
        order.setOrderMoney(validCard.getCardPrice());
        order.setOrderType(OrderState.VALID_CARD_TYPE.getState());//次卡类型
        save(order);
        rabbitTemplate.convertAndSend("card-order-dead-queue",orderNum);
        //记录日志
        OrderLog log = new OrderLog();
        log.setLogUser(userInfo.getUserName()+":"+userInfo.getUserPhone());
        log.setLogDesc("用户有效期卡下订单");
        log.setLogTime(DateUtil.dateTimeToString(new Date()));
        log.setOrderNum(orderNum);
        rabbitTemplate.convertAndSend("order-log-queue",log);
        ValidCardOrderDto dto = BeanUtil.toBean(order, ValidCardOrderDto.class);
        return dto;
    }

    /**
     * 次卡支付宝支付回调
     * @param params
     */
    @Override
    public void notifyCountCardHandler(Map<String, String> params) throws AlipayApiException {
        //验签，校验支付宝方的请求是不是伪造的
        boolean rsa2 = AlipaySignature.rsaCheckV1(params, alipayConfiguration.getAlipayPublicKey(), "utf-8", "RSA2");
        if (!rsa2) throw new WoniuxyException(500, "伪造非法请求，执行失败");
        String orderNum = params.get("out_trade_no");
        Order orderInfo = getById(orderNum);
        //改订单状态
        orderInfo.setOrderState(OrderState.IS_PAID.getState());//已购买
        orderInfo.setOrderPayTime(DateUtil.dateTimeToString(new Date()));
        updateById(orderInfo);
        //记录日志
        OrderLog log = new OrderLog();
        log.setLogUser("支付宝异步回调次卡订单操作");
        log.setLogDesc("订单已支付");
        log.setLogTime(DateUtil.dateTimeToString(new Date()));
        log.setOrderNum(orderNum);
        rabbitTemplate.convertAndSend("order-log-queue",log);
        rabbitTemplate.convertAndSend("count-card-order-process-queue",orderNum);//生成次卡订单进度
    }

    /**
     * 有效期卡订单支付宝回调
     * @param params
     */
    @Override
    public void notifyValidCardHandler(Map<String, String> params) throws AlipayApiException {
        //验签，校验支付宝方的请求是不是伪造的
        boolean rsa2 = AlipaySignature.rsaCheckV1(params, alipayConfiguration.getAlipayPublicKey(), "utf-8", "RSA2");
        if (!rsa2) throw new WoniuxyException(500, "伪造非法请求，执行失败");
        String orderNum = params.get("out_trade_no");
        Order orderInfo = getById(orderNum);
        //改订单状态
        orderInfo.setOrderState(OrderState.IS_PAID.getState());//已购买
        orderInfo.setOrderPayTime(DateUtil.dateTimeToString(new Date()));
        updateById(orderInfo);
        //记录日志
        OrderLog log = new OrderLog();
        log.setLogUser("支付宝异步回调有效期卡订单操作");
        log.setLogDesc("订单已支付");
        log.setLogTime(DateUtil.dateTimeToString(new Date()));
        log.setOrderNum(orderNum);
        rabbitTemplate.convertAndSend("order-log-queue",log);
        rabbitTemplate.convertAndSend("valid-card-order-process-queue",orderNum);//生成次卡订单进度
    }


}
